import {
    defineStore,
} from "pinia"
import {
    reactive,
    ref,
    readonly
} from "vue"
import {
    login,
    getIfon
} from "@/api/user.js"


export const useUserStore = defineStore("UserInfo", () => {
    // 学生数据
    const userInfo = reactive({})
    const readUserInfo = readonly(userInfo)
    // 是否加载中
    const loading = ref(false);
    // 是否登录成功
    const isLogin = ref(false)
    // 登录
    const Login = async (Info) => {
        loading.value = true
        const {
            data
        } = await login({
            ...Info
        })
        if (!data) {
            loading.value = false
            return
        }
        if (data.state === 2) {
            ElMessage.error('登录失败,请重新输入账号密码')
            loading.value = false
            return {
                start: 1,
                data
            }
        } else if (data.state === 1) {
            const token = data.token
            sessionStorage.setItem("token", token)
            loading.value = false
            isLogin.value = true
            ElMessage({
                message: '登录成功，欢迎使用宿舍管理系统',
                type: 'success',
            })
            await getUserInfo()
            return {
                start: 0,
                data
            }
        }
    }

    // 获取学生数据
    const getUserInfo = async () => {
        if (!sessionStorage.getItem("token")) {
            return
        }
        const {
            data
        } = await getIfon()
        if (data) {
            for (const key in data) {
                userInfo[key] = data[key]
            }
        }
    }
    return {
        userInfo,
        readUserInfo,
        loading,
        isLogin,
        Login,
        getUserInfo
    }
}, {
    persist: {
        enabled: true,
        key: 'userInfo',
        // 指定存储的方式，这里是 sessionStorage
        storage: sessionStorage,
        paths: ['userInfo'],
    },
})